﻿using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SelfService.XinXing
{
    public static class Utility
    {
        /// <summary>
        /// 对象序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="isUtf8"></param>
        /// <returns></returns>
		public static string ToXml(this object obj, bool isUtf8 = true)
        {
            if (obj == default) return null;
			StringBuilder stringBuilder = new StringBuilder(50);
            XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
            xmlSerializerNamespaces.Add(string.Empty, string.Empty);
            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Encoding = isUtf8 ? Encoding.UTF8 : Encoding.GetEncoding("GB2312")
            };
            XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings);
            xmlSerializer.Serialize(xmlWriter, obj, xmlSerializerNamespaces);
            xmlWriter.Flush();
            xmlWriter.Close();
            return stringBuilder.ToString();
		}

        /// <summary>
        /// XML反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool XmlTryParseToObject<T>(this string xml, out T data)
        {
            data = default;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                using StringReader stringReader = new StringReader(xml);
                data = (T)xmlSerializer.Deserialize(stringReader);
                return data != null;
            }
            catch (Exception e)
            {
                return false;
            }
        }
	}
}
